package com.example.administrator.szb.fragments.fragment_forXM;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.ProductDetail2Activity;
import com.example.administrator.szb.activity.ProductDetailActivity;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.fragments.base.BaseFragment;
import com.example.administrator.szb.bean.MyXMBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.QTLog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.api.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by D N on 2017/10/30.
 * 金融顾问收到的项目和发出的项目
 */

public class FragmentXM extends BaseFragment {
    View view;
    int type;//type =1,我发出的项目，type =2 ,我收到的项目
    @Bind(R.id.xmgl_recyclerview)
    RecyclerView xmglRecyclerview;
    @Bind(R.id.xmgl_swiperefreshlayout)
    SmartRefreshLayout xmglSwiperefreshlayout;

    MyXMBean myXMBean;
    private int current_page = 1;
    private int per_page = 10;

    BaseAdapter<MyXMBean.DataBean.BBean> adapter_B;
    BaseAdapter<MyXMBean.DataBean.ABean> adapter_A;
    View footerview;
    ArrayList<MyXMBean.DataBean.BBean> mdata_b = new ArrayList<>();
    ArrayList<MyXMBean.DataBean.ABean> mdata_a = new ArrayList<>();


    int wz=0;//用于判断是否加了head,而导致position 的位置不对
    View error_head;
    private boolean isFirstEnter = true;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getArguments().getInt("type");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.xmgl_fragment, container, false);
        ButterKnife.bind(this, view);
        footerview = LayoutInflater.from(getActivity()).inflate(R.layout.view_wd_footer, null);
        footerview.setVisibility(View.INVISIBLE);

        //requestData();
        initView();
        return view;
    }

    private void initView() {
        initRefreshLayout();
        //initRecyclerview();
    }
    /**
     * 开启刷新监听
     */
    private void initRefreshLayout() {
//        xmglSwiperefreshlayout.setColorSchemeResources(R.color.zhutise);
//        xmglSwiperefreshlayout.post(new Runnable() {
//            @Override
//            public void run() {
//                current_page = 1;
//                xmglSwiperefreshlayout.setRefreshing(true);
//                try {
//                    requestData(0);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//
//        xmglSwiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                current_page = 1;
//                xmglSwiperefreshlayout.setRefreshing(true);
//                try {
//                    requestData(0);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });


        if (isFirstEnter) {
            isFirstEnter = false;
            xmglSwiperefreshlayout.autoRefresh();
        }
        xmglSwiperefreshlayout.setEnableLoadMore(true);//是否启用上拉加载功能
        xmglSwiperefreshlayout.setEnableLoadMoreWhenContentNotFull(true);//是否在列表不满一页时候开启上拉加载功能


        xmglSwiperefreshlayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //refreshlayout.setLoadmoreFinished(false);//恢复上拉状态
                // Toasts.show(getActivity(), "加载更多啊", Toast.LENGTH_SHORT);
                requestData(1);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                current_page = 1;
                requestData(0);
                //refreshlayout.finishRefresh();
            }
        });
    }

    private void requestData(final int isRefreshOrMore){

        HashMap<String,Object> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("users_id", SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("current_page",""+current_page);
        map.put("per_page",""+per_page);
        String url = URLAddress.URLBASE + URLAddress.URL_XM;
        HttpUtils.post2(activity,url, map, 0, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {
                try {
                    myXMBean = JSON.parseObject(str,new TypeReference<MyXMBean>(){});
                } catch (Exception e) {
                    str = str.replace("\"indentInfo\":[]","\"indentInfo\":null");
                    str = str.replace("\"a\":null","\"a\":[]");
                    str = str.replace("\"b\":null","\"b\":[]");
                    QTLog.e(str);
                    myXMBean = JSON.parseObject(str,new TypeReference<MyXMBean>(){});
                }
                if (myXMBean.getResult() == 1){


                    if (isRefreshOrMore == 0) {
                        mdata_a.clear();
                        if (myXMBean.getData().getA()!=null){
                            mdata_a.addAll(myXMBean.getData().getA());
                        }


                        mdata_b.clear();
                        if (myXMBean.getData().getB()!=null){
                            mdata_b.addAll(myXMBean.getData().getB());
                        }

                        xmglSwiperefreshlayout.finishRefresh();
                        current_page = current_page+1;
                        // Toasts.show(getActivity(), "刷新成功", Toast.LENGTH_SHORT);
                    }else if(isRefreshOrMore == 1){
                        if (myXMBean.getData().getA()!=null&&myXMBean.getData().getA().size()>0 && type == 1){
                            current_page = current_page+1;
                            mdata_a.addAll(myXMBean.getData().getA());
                        }else{
                            // Toasts.show(getActivity(), "没有数据了", Toast.LENGTH_SHORT);
                        }

                        if (myXMBean.getData().getB()!=null&&myXMBean.getData().getB().size()>0 && type == 2){
                            current_page = current_page+1;
                            mdata_b.addAll(myXMBean.getData().getB());

                        }else{
                            // Toasts.show(getActivity(), "没有数据了", Toast.LENGTH_SHORT);
                        }



                        xmglSwiperefreshlayout.finishLoadmore(true);//结束加载（加载失败）
                    }
                    initRecyclerview();
                    if (type == 1){
                        adapter_A.notifyDataSetChanged();
                    }else if(type == 2){
                        adapter_B.notifyDataSetChanged();
                    }
                }


            }

            @Override
            public void onFailure(int requestCode, String str) {
                xmglSwiperefreshlayout.finishRefresh(false);
            }
        });


        /*HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, MyXMBean.class, URLAddress.URLBASE + URLAddress.URL_XM, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                QTLog.e("测试进来没有");

                myXMBean = (MyXMBean) response;

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                error.toString();
            }
        });*/

    }

    private void initRecyclerview() {
        xmglRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));

        if (type == 2){
             if (adapter_B==null){
                 adapter_B = new BaseAdapter<MyXMBean.DataBean.BBean>(getActivity(), mdata_b) {
                     @Override
                     public void convert(int position, BaseViewHolder holder, MyXMBean.DataBean.BBean dataBean) {


                         ((TextView)holder.getView(R.id.textView144)).setText(dataBean.getBusinessName());
                         ((TextView)holder.getView(R.id.textView148)).setText(dataBean.getStatus());
                         HashMap<Integer, MyXMBean.YWInfoData> map = (HashMap<Integer, MyXMBean.YWInfoData>) dataBean.getIndentInfo();
                         String info = "";
                         for (int i = 0; i < dataBean.getBusformId().size(); i++) {
                             info = info + map.get(dataBean.getBusformId().get(i)).getKeyName() +":"+ map.get(dataBean.getBusformId().get(i)).getValueName() +"     ";
                         }

                         ((TextView)holder.getView(R.id.textView149)).setText(info);
                         if (dataBean.getBusformId().size() == 0){
                             ((TextView) holder.getView(R.id.textView149)).setText("联系人："+dataBean.getName());
                         }
                     }

                     @Override
                     public int getLayoutId(int viewType) {
                         return R.layout.view_my_xmxq_userinfo;
                     }
                 };
                 adapter_B.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                     @Override
                     public void onItemClick(View view, int position) {
                         godetail(1,mdata_b.get(position).getId());
                     }
                 });
             }



            if (mdata_b.size() == 0) {
                error_head = LayoutInflater.from(getActivity()).inflate(R.layout.view_item_error, xmglRecyclerview, false);
                adapter_B.addHeaderView(error_head);
                ((TextView)error_head.findViewById(R.id.text_view_error)).setText("您尚未发布项目哦");
               //messageViewShow.setVisibility(View.GONE);
                wz = 1;
            }else{
                //adapter_B.addFootView(footerview);
                //loadMore();//开启加载更多监听
            }

            xmglRecyclerview.setAdapter(adapter_B);
        }else{
             if (adapter_A==null){
                 adapter_A = new BaseAdapter<MyXMBean.DataBean.ABean>(getActivity(), mdata_a) {
                     @Override
                     public void convert(int position, BaseViewHolder holder, MyXMBean.DataBean.ABean dataBean) {
                         if(type == 1){
                             holder.getView(R.id.textView161).setVisibility(View.VISIBLE);
                             ((TextView)holder.getView(R.id.textView161)).setText("申请人："+dataBean.getName());
                         }
                         ((TextView)holder.getView(R.id.textView144)).setText(dataBean.getBusinessName());
                         ((TextView)holder.getView(R.id.textView148)).setText((String)dataBean.getStatus());
                         HashMap<Integer, MyXMBean.YWInfoData> map = (HashMap<Integer, MyXMBean.YWInfoData>) dataBean.getIndentInfo();
                         String info = "";
                         for (int i = 0; i < dataBean.getBusformId().size(); i++) {
                             info = info + map.get(dataBean.getBusformId().get(i)).getKeyName() +":"+ map.get(dataBean.getBusformId().get(i)).getValueName() +"     ";
                         }

                         if (dataBean.getBusformId().size() == 0){
                             ((TextView) holder.getView(R.id.textView149)).setText(dataBean.getName());
                         }
                         ((TextView)holder.getView(R.id.textView149)).setText(info);
                     }

                     @Override
                     public int getLayoutId(int viewType) {
                         return R.layout.view_my_xmxq_userinfo;
                     }
                 };
                 adapter_A.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                     @Override
                     public void onItemClick(View view, int position) {
                         godetail(2,mdata_a.get(position).getId());
                     }
                 });
             }


            if (mdata_a.size() == 0) {
                error_head = LayoutInflater.from(getActivity()).inflate(R.layout.view_item_error, xmglRecyclerview, false);
                adapter_A.addHeaderView(error_head);
                ((TextView)error_head.findViewById(R.id.text_view_error)).setText("尚未有他人向您发起项目");
                //messageViewShow.setVisibility(View.GONE);
                wz = 1;
            }else{
                //adapter_A.addFootView(footerview);
                //loadMore();//开启加载更多监听
            }
            xmglRecyclerview.setAdapter(adapter_A);
        }


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public void godetail(int types,int id){
        Class c;
        if (types==1){//我发出的
            c = ProductDetailActivity.class;
        }else {//我收到的
            c = ProductDetail2Activity.class;
        }
        Intent intent = new Intent(getActivity(),c);
        intent.putExtra("dd_id",id);
        intent.putExtra("genre",types);
        startActivity(intent);
    }
}
